from fastapi import APIRouter, Query
from typing import Optional
from db.models.customer import Customer  # 确保导入路径正确
from ApiResponse import ApiResponse, PageResult
from tortoise.contrib.pydantic import pydantic_model_creator

# 创建路由
customer_router = APIRouter()

# 从Tortoise模型自动生成Pydantic响应模型
CustomerPydantic = pydantic_model_creator(
    Customer,
    name="Customer",
    include=("cusid", "telephone", "address", "cusname"),
    # 将可能为空的字段设为可选
    # optional=("create_time", "update_time", "cusname", "ename", "code",
    #           "connector", "telephone", "address", "level", "region",
    #           "channel", "isin", "statu", "owner", "paytype",
    #           "create_by", "update_by", "remark")
)


@customer_router.get(
    "/list",
    response_model=ApiResponse[PageResult[CustomerPydantic]],
    summary="客户分页查询"
)
async def get_customer_list(
        cusname: Optional[str] = Query(None, description="客户名称(模糊查询)"),
        page: int = Query(1, ge=1, description="页码"),
        limit: int = Query(20, ge=1, le=100, description="每页数量")
):
    """
    客户分页查询接口 - 直接使用数据库模型

    参数:
    - cusname: 客户名称，支持模糊查询
    - page: 页码，从1开始
    - limit: 每页数量，最大100
    """
    try:
        # 构建查询条件
        query = Customer.filter(del_flag="0")  # 只查询未删除的记录

        # 按客户名称模糊查询
        if cusname:
            query = query.filter(cusname__icontains=cusname)

        # 获取总数
        total_count = await query.count()

        # 分页查询
        offset = (page - 1) * limit
        customers = await query.offset(offset).limit(limit).order_by("-create_time")

        # 直接使用数据库模型，FastAPI会自动序列化
        page_result = PageResult.create(rows=customers, count=total_count)

        # 返回统一格式响应
        return ApiResponse.ok(data=page_result, msg="查询成功")

    except Exception as e:
        # 返回错误响应
        return ApiResponse.error(error_code=500, error_msg=f"查询客户列表失败: {str(e)}")
